package cn.sharp.bbs.service.impl;

import cn.sharp.bbs.common.TokenUtils;
import cn.sharp.bbs.dao.PublishArticleDao;
import cn.sharp.bbs.dao.gen.ImgMapper;
import cn.sharp.bbs.dao.gen.PostMapper;
import cn.sharp.bbs.dao.gen.PostversionMapper;
import cn.sharp.bbs.dao.gen.UserMapper;
import cn.sharp.bbs.entity.BO.*;
import cn.sharp.bbs.entity.DO.*;
import cn.sharp.bbs.event.LoginEvent;
import cn.sharp.bbs.event.PostCreateEvent;
import cn.sharp.bbs.event.PostEvent;
import cn.sharp.bbs.service.PostService;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 杨择润
 * @create 2022-07-11 7:59
 */
@Transactional
@Service
public class PostServiceImpl implements PostService , ApplicationEventPublisherAware {
    @Resource
    PublishArticleDao publishArticleDao;
    @Resource//注入属性，必须要加
    PostMapper postMapper;
    @Resource
    PostversionMapper postversionMapper;
    @Resource
    ImgMapper imgMapper;
    @Resource
    UserMapper userMapper;

    private ApplicationEventPublisher eventPublisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
    }


    @Override
    public PublishArticle publishArticle(PublishArticle publishArticle) {
        //进行post对应赋值
        Post post = new Post();
        Postversion postversion=new Postversion();
        //把对应属性的值赋予，相当于post.setType(publishArticle.getType());
        BeanUtils.copyProperties(publishArticle,post);

        //插入post
        postMapper.insert(post);
        //进行postversion赋值
        //postid赋值
        publishArticle.setPostId(post.getId());
        BeanUtils.copyProperties(publishArticle,postversion);
        postversion.setTitle(publishArticle.getA_title());
        postversion.setCont(publishArticle.getA_html());
        //获取当前时间值
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        postversion.setTime(date);
        postversionMapper.insert(postversion);
        //填充图片
        Img img=new Img();
        String testUrl=publishArticle.getA_html();
        if(testUrl.contains("<img")){
            String result1 = testUrl.substring(testUrl.indexOf("<img src=\"") + 10);
            System.out.println("result = " + result1);
            //获取固定字符串之前的字符串
            String result = result1.substring(0,result1.indexOf("\""));
            System.out.println("result = " + result);
            if(!result.equals("")){
                img.setPath(result);
                img.setPverId(postversion.getId());
                imgMapper.insert(img);
            }
        }


//        eventPublisher.publishEvent(new PostCreateEvent(this,post.getId()));
        return publishArticle;
    }

    @Override
    public PublishArticle republishArticle(PublishArticle publishArticle) {
        //进行post对应赋值
        Post post = new Post();
        Postversion postversion=new Postversion();
        //把对应属性的值赋予，相当于post.setType(publishArticle.getType());
        BeanUtils.copyProperties(publishArticle,post);
        post.setId(publishArticle.getPostId());

        //插入post
        postMapper.updateByPrimaryKey(post);
        //进行postversion赋值
        //postid赋值
        BeanUtils.copyProperties(publishArticle,postversion);
        postversion.setTitle(publishArticle.getA_title());
        postversion.setCont(publishArticle.getA_html());
        //获取当前时间值
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        postversion.setTime(date);

        postversionMapper.updateByPrimaryKey(postversion);
        return publishArticle;
    }

    @Override
    public void uploadImg(Img img, ImgResultDto imgResultDto, List<MultipartFile> list) throws FileNotFoundException {
        //得到项目目录绝对路径
        String imgAbsolutePath = new File(ResourceUtils.getURL("file:").getPath()).getAbsolutePath()
                +"/assets/img/"; // 图片存储的本地地址 需配置静态目录 TODO: 部署
        String[] urlData = new String[5]; // 设置一次性传5张，其实一次一张就够用了，前端只用到了data[0]
        int index = 0;
        try {
            for(MultipartFile image : list) {
                //获取原始文件名，比如你上传的是　图片．jpg,则fileName＝图片．jpg
                String fileName = image.getOriginalFilename();
                if("".equals(fileName)) {
                    continue;
                }
                //为了保证文件名不一致，因此文件名称使用当前的时间戳和4位的随机数，还有原始文件名组成
                //觉得实际的企业开发不应当使用原始文件名，否则上传者使用一些不好的名字，对于下载者就不好了．
                //这里为了调试方便，可以加上．
                String finalFileName =  (new Date().getTime()) + Math.round(Math.random() * 1000)  //文件名动态部分
                        + fileName; //文件名　原始文件名
               File newfile = new File( imgAbsolutePath + finalFileName);
                //保存文件到项目静态文件夹
                image.transferTo(newfile);
                //这里的路径是项目路径＋文件路径＋文件名称
                //这么写不是规范的做法，项目路径应是放在前端处理，只需要发送相对路径和文件名称即可，项目路径由前端加上．
                urlData[index++] = "/api/assets/img/" + finalFileName; // 前端的图片访问地址
                System.out.println(finalFileName);
                //设置异常代号
                imgResultDto.setErrno(0);
            }
            imgResultDto.setData(urlData);
            //返回Ｄto
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    @Override
    public List<PostDto> selectArticle(Long id, String s) {
        List<PostDto> postDtos=new ArrayList<PostDto>() ;
        List<Postversion> postversionlist =publishArticleDao.selectArticle(s);
        for (Postversion postversion:postversionlist){
            //postdto初始化
            PostDto postDto=new PostDto();
            //内容，标题等赋值
            BeanUtils.copyProperties(postversion,postDto);
            postDto.setContent(postversion.getCont());
            //分区等赋值
            Post post=postMapper.selectByPrimaryKey(postversion.getPostId());
            BeanUtils.copyProperties(post,postDto);
            //作者名字，id赋值
            postDto.setAuthorId(post.getUserId());
            User user=userMapper.selectByPrimaryKey(post.getUserId());
            postDto.setAuthorName(user.getName());
            //标签赋值
            List<Label> labels=publishArticleDao.selectTabs(post.getId());
            postDto.setLabels(labels);
            //like赋值
            Like like=new Like();
            like.setPostId(postversion.getPostId());
            like.setUserId(id);
            postDto.setLike(publishArticleDao.trueLike(like));
            //点赞数 傻逼long类型
            postDto.setLikeCount((long)publishArticleDao.likeCount(like));
            //collect赋值
            Collectpost collectpost=new Collectpost();
            collectpost.setPostId(postversion.getPostId());
            collectpost.setUserId(id);
            postDto.setCollect(publishArticleDao.trueCollect(collectpost));
            //collectCount赋值
            postDto.setCollectCount((long)publishArticleDao.collectCount(collectpost));
            //followPost赋值
            Followpost followpost=new Followpost();
            followpost.setPostId(postversion.getPostId());
            followpost.setPostId(id);
            postDto.setFollowPost(publishArticleDao.truefollowPost(followpost));
            //followPostCount赋值
            postDto.setFollowPostCount((long)publishArticleDao.followCount(followpost));
            //followAuthor赋值
            Followuser followuser=new Followuser();
            followuser.setUserId(id);
            followuser.setUserFollowed(post.getUserId());
            postDto.setFollowAuthor(publishArticleDao.truefollowUser(followuser));
            //添加图片路径

            postDto.setImg(publishArticleDao.getImgpath(postversion.getId()));
            postDtos.add(postDto);

        }

        return postDtos;
    }

    @Override
    public List<PostDto> selectUserArticle(Long id, String s) {
        List<PostDto> postDtos=new ArrayList<PostDto>() ;
        List<Postversion> postversionlist =publishArticleDao.selectUserArticle(id);
        for (Postversion postversion:postversionlist){
            //postdto初始化
            PostDto postDto=new PostDto();
            //内容，标题等赋值
            BeanUtils.copyProperties(postversion,postDto);
            postDto.setContent(postversion.getCont());
            //分区等赋值
            Post post=postMapper.selectByPrimaryKey(postversion.getPostId());
            BeanUtils.copyProperties(post,postDto);
            //作者名字，id赋值
            postDto.setAuthorId(post.getUserId());
            User user=userMapper.selectByPrimaryKey(post.getUserId());
            postDto.setAuthorName(user.getName());
            //标签赋值
            List<Label> labels=publishArticleDao.selectTabs(post.getId());
            postDto.setLabels(labels);
            //like赋值
            Like like=new Like();
            like.setPostId(postversion.getPostId());
            like.setUserId(id);
            postDto.setLike(publishArticleDao.trueLike(like));
            //点赞数 傻逼long类型
            postDto.setLikeCount((long)publishArticleDao.likeCount(like));
            //collect赋值
            Collectpost collectpost=new Collectpost();
            collectpost.setPostId(postversion.getPostId());
            collectpost.setUserId(id);
            postDto.setCollect(publishArticleDao.trueCollect(collectpost));
            //collectCount赋值
            postDto.setCollectCount((long)publishArticleDao.collectCount(collectpost));
            //followPost赋值
            Followpost followpost=new Followpost();
            followpost.setPostId(postversion.getPostId());
            followpost.setPostId(id);
            postDto.setFollowPost(publishArticleDao.truefollowPost(followpost));
            //followPostCount赋值
            postDto.setFollowPostCount((long)publishArticleDao.followCount(followpost));
            //followAuthor赋值
            Followuser followuser=new Followuser();
            followuser.setUserId(id);
            followuser.setUserFollowed(post.getUserId());
            postDto.setFollowAuthor(publishArticleDao.truefollowUser(followuser));
            //添加图片路径

            postDto.setPath(publishArticleDao.getImgpath(postversion.getId()));
            postDtos.add(postDto);

        }

        return postDtos;
    }
    @Override
    public PostDto selectArticleBypostid(Long id) {


            Postversion postversion=publishArticleDao.searchArticleByid(id);
            System.out.println(postversion);
            //postdto初始化
            PostDto postDto=new PostDto();
            //内容，标题等赋值
            BeanUtils.copyProperties(postversion,postDto);
            postDto.setContent(postversion.getCont());
            //分区等赋值
            Post post=postMapper.selectByPrimaryKey(postversion.getPostId());
            BeanUtils.copyProperties(post,postDto);
            //作者名字，id赋值
            postDto.setAuthorId(post.getUserId());
            User user=userMapper.selectByPrimaryKey(post.getUserId());
            postDto.setAuthorName(user.getName());
            //标签赋值
            List<Label> labels=publishArticleDao.selectTabs(post.getId());
            postDto.setLabels(labels);
            //like赋值
            Like like=new Like();
            like.setPostId(postversion.getPostId());
            like.setUserId(id);
            postDto.setLike(publishArticleDao.trueLike(like));
            //点赞数 傻逼long类型
            postDto.setLikeCount((long)publishArticleDao.likeCount(like));
            //collect赋值
            Collectpost collectpost=new Collectpost();
            collectpost.setPostId(postversion.getPostId());
            collectpost.setUserId(id);
            postDto.setCollect(publishArticleDao.trueCollect(collectpost));
            //collectCount赋值
            postDto.setCollectCount((long)publishArticleDao.collectCount(collectpost));
            //followPost赋值
            Followpost followpost=new Followpost();
            followpost.setPostId(postversion.getPostId());
            followpost.setPostId(id);
            postDto.setFollowPost(publishArticleDao.truefollowPost(followpost));
            //followPostCount赋值
            postDto.setFollowPostCount((long)publishArticleDao.followCount(followpost));
            //followAuthor赋值
            Followuser followuser=new Followuser();
            followuser.setUserId(id);
            followuser.setUserFollowed(post.getUserId());
            postDto.setFollowAuthor(publishArticleDao.truefollowUser(followuser));
            //添加图片路径
            postDto.setPath(publishArticleDao.getImgpath(postversion.getId()));

        return postDto;
    }


    @Override
    public List<CommentDto> getArticlecomment(Long id) {
        List<Comment> comments=publishArticleDao.getArticleComment(id);
        List<CommentDto> commentDtos=new ArrayList<CommentDto>() ;
        for(Comment comment:comments){

            if(!(comment.getPcomId()==null)){
                continue;
            }
            CommentDto commentDto=new CommentDto();

            //评论为1级评论找对应二级评论
            List<CommentDto> commentDtos1=new ArrayList<CommentDto>() ;
            List<Comment> comments2=publishArticleDao.getArticleComment2(comment.getId());
            if(!(comments2.isEmpty())){

                for(Comment comment2:comments2){

                    CommentDto commentDto1=new CommentDto();
                    User user1=userMapper.selectByPrimaryKey(comment2.getUserId());
                    BeanUtils.copyProperties(comment2,commentDto1);
                    BeanUtils.copyProperties(user1,commentDto1);
                    commentDtos1.add(commentDto1);
                }
            }
            commentDto.setChil(commentDtos1);



            BeanUtils.copyProperties(comment,commentDto);

            User user=userMapper.selectByPrimaryKey(comment.getUserId());

            BeanUtils.copyProperties(user,commentDto);

            commentDtos.add(commentDto);

        }


        return commentDtos;
    }

    /**
     * 实际发帖操作
     *
     *
     */
//    @Override
//    public String doPost(PublishArticle entity) {
//        eventPublisher.publishEvent(new PostEvent(this, entity.getId()));
//        return TokenUtils.loginSign(String.valueOf(entity.getU_id()), entity.getU_pwd());
//    }
//}
    public static String getText(String richText) {
        String regx = "(<.+?>)|(</.+?>)";
        Matcher matcher = Pattern.compile(regx).matcher(richText);
        while (matcher.find()) {
            // 替换图片
            richText = matcher.replaceAll("").replace(" ", "");
        }
        return richText;
    }
}
